﻿using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Text;

namespace TCP.SocketHelper
{
    public static class SocketExtension
    {
        /// <summary>
        /// 获取该socket的远端连接IP
        /// <para>暂时只适用于IPv4</para>
        /// </summary>
        /// <param name="socket"></param>
        /// <returns></returns>
        public static string GetIP(this Socket socket)
        {
            string ip = "Unknow";
            if(socket.RemoteEndPoint!=null && socket.RemoteEndPoint.AddressFamily == AddressFamily.InterNetwork)
            {
                ip = socket.RemoteEndPoint.ToString().Split(':')[0];
            }

            return ip;
        }

        /// <summary>
        /// 获取该socket的远端连接端口
        /// <para>暂时只适用于IPv4</para>
        /// </summary>
        /// <param name="socket"></param>
        /// <returns></returns>
        public static int GetPort(this Socket socket)
        {
            int port = 0;
            if (socket.RemoteEndPoint != null && socket.RemoteEndPoint.AddressFamily == AddressFamily.InterNetwork)
            {
                int.TryParse(socket.RemoteEndPoint.ToString().Split(':')[1], out port);
            }
            return port;
        }
    }
}
